#include "stdafx.h"
 

#include "./base.h"

#ifdef WIN32
#include "winsock2.h"
#else
 	#include <net/if.h>
	#include <sys/ioctl.h>
	#include <sys/time.h>
	#include <map>
	#include <vector> 
#endif



void base::MySleep(int Millisecond)
{
#ifdef WIN32
		Sleep( Millisecond );
#else
		usleep( 1000 * Millisecond ); 
#endif

}


string base::GetCurrentProcessName()
{

	char  path[128], processName[32];
	memset(path, 0, 128);
	memset(processName, 0, 32);

	size_t sz = get_executable_path(path, processName, 128);
	if( sz <= 0 ) return "";

	return processName;

}

string base::GetCurrentProcessPath() // ����·��
{
	static string g_curProcessPath ;

#ifdef WIN32
	if( g_curProcessPath.empty()  ){
 
		char t_tttt_t[24] ; 
 
 		if( g_curProcessPath.empty()  ){
			char bbb[MAX_PATH] ;
			string vvv ;
			::GetModuleFileName(NULL, bbb, MAX_PATH ) ;
			vvv = bbb ;
			char  * prchr = strrchr(bbb, '\\' );
			base::Replace(vvv, prchr, ""); 
			g_curProcessPath = vvv ;
		}
	}
#else
	char szWorkDir[256] = {0} ;  
    
    if(getcwd(szWorkDir, 260))  
    {  
       g_curProcessPath = szWorkDir ;  
    }  
#endif
	return g_curProcessPath ;
}

unsigned int base::get_tick_count()
{
#ifdef WIN32
	return ::GetTickCount() ;
#else
	struct timeval tv ;
	gettimeofday(&tv,NULL);
	return (tv.tv_sec*1000 + tv.tv_usec/1000);
#endif
}

bool base::is_exist_file(const char *path)  
{     
    struct stat statbuff;   
    if(stat(path, &statbuff) < 0){   
        return false; 
    }  
    else { 
  		return true; 
    } 
}

bool base::is_dir_exit(const char * dir_path)
{
	if( dir_path == NULL) return false;
	
#ifdef WIN32
#else
	if( opendir(dir_path) == NULL ) 
		return false;
#endif	
	return true;
}

int base::copy_file(char * srcProgram, char *newProgram)  
{   
  
    int fin = open(srcProgram, O_RDONLY, 0777);  
    int fout = open(newProgram, O_WRONLY|O_CREAT, 0777);  
  
    char buff[1024] = {'\0'};  
    int len = 0;  
    while((len = read(fin, buff, sizeof(buff))) > 0)  
    {  
		write(fout, buff, len);  
    }  
  
    close(fin);  
    close(fout);  
  
    return 0;  
}

int base::HStatFileSize(const char *pszFileName)
{
#ifdef WIN32 
    if( _access(pszFileName,0)!=-1) return  0 ;
    struct _stat  buff ; 
    if(_stat(pszFileName,&buff) !=-1){
	 return buff.st_size ; 
    }
#else
 if( access(pszFileName,0)!=-1) return  0 ;
    struct stat  buff ; 
    if(stat(pszFileName,&buff) !=-1){
	 return buff.st_size ; 
    }
#endif
  return  0;
} 

void base::HMkDir(const char * path)
{ 
	if(path==0|| strlen(path)==0 ) return  ; 

	try
	{
		char * pp = (char*)path;
		char tmpdir[260];
		int  len ;
		while(*pp)
		{
		if(*pp!='/'){
			pp++ ; continue;
		};
		pp++  ;
		len = pp-path ; 
		strncpy(tmpdir,path,pp-path) ; 
		tmpdir[len] = 0 ; 
		#ifndef WIN32
            if((access(tmpdir,0 ))== -1) mkdir(tmpdir,0777)   ;
		#else
            if((_access(tmpdir,0 ))== -1) _mkdir(tmpdir)   ;
		#endif
		} 
	} 
	catch(...)
	{
	}
}


void base::get_file_list(const char* spec_filter,std::vector<std::string> & lst) 
{
#ifdef WIN32 
	if(spec_filter ==NULL || strlen(spec_filter)==0)  return  ; 

	string  strPath =  spec_filter ;
	strPath +=   "\\*" ;
	struct _finddata_t  fileinfo  ; 
	intptr_t  ifind_handle = _findfirst(strPath.c_str(),&fileinfo) ; 
	if(ifind_handle==-1) return ;

	do
	{ 	
		if(strcmp(fileinfo.name ,".")  ==0) continue ; 
		if(strcmp(fileinfo.name ,"..")  ==0) continue ;
		//sprintf(full_path,"%s%s",spec_path,fileinfo.name) ;
		if( (fileinfo.attrib & _A_NORMAL) ) { //is path
			continue; 
		}
		//printf("%s\n",fileinfo.name);
		lst.push_back(fileinfo.name);
	}
	while(_findnext(ifind_handle,& fileinfo)==0);

	_findclose( ifind_handle) ;

	//sort(lst.begin(),lst.end(),greater);
#else
	DIR * dp;
	
	lst.clear();
	
	struct dirent * dirp;
	
	if( (dp = opendir(spec_filter )) == NULL )
	{
		base::my_printf( "open %s error \n",  spec_filter  );
		return ;
	}
	
	while( (dirp = readdir(dp)) != NULL )
	{
		if( dirp->d_type == 8 ) //��ͨ�ļ� : 4 :��ʾ�ļ����� 8 �� ��ͨ�ļ�  0�� ��ʾδ֪�豸
			lst.push_back( dirp->d_name );
	}


#endif 
	 
 } 
 
 
 void base::read_file(string dirname, std::vector<string> & aryfiles)
{ 
#ifndef WIN32
	DIR * dp;
	
	aryfiles.clear();
	
	struct dirent * dirp;
	
	if( (dp = opendir(dirname.c_str())) == NULL )
	{
		base::my_printf( "open %s error \n", (char*)dirname.c_str() );
		return ;
	}
	
	while( (dirp = readdir(dp)) != NULL )
	{
		if( dirp->d_type == 8 ) //��ͨ�ļ� : 4 :��ʾ�ļ����� 8 �� ��ͨ�ļ�  0�� ��ʾδ֪�豸
			aryfiles.push_back( dirp->d_name );
	}
#else
	 
	get_file_list(dirname.c_str(), aryfiles); 
#endif
}


bool GetLocalIP(char* ip)  
{  
#ifdef WIN32
	//1.��ʼ��wsa  
    WSADATA wsaData;  
    int ret=WSAStartup(MAKEWORD(2,2),&wsaData);  
    if (ret!=0)  
    {  
        return false;  
    }  
    //2.��ȡ������  
    char hostname[256];  
    ret=gethostname(hostname,sizeof(hostname));  
    if (ret==SOCKET_ERROR)  
    {  
        return false;  
    }  
    //3.��ȡ����ip  
    HOSTENT* host=gethostbyname(hostname);  
    if (host==NULL)  
    {  
        return false;  
    }  
    //4.ת��Ϊchar*����������  
    strcpy(ip,inet_ntoa(*(in_addr*)*host->h_addr_list));  

	return true;
#else
	//int i=0;
	//int sockfd;
	//struct ifconf ifconf;
	//char buf[512];
	//struct ifreq *ifreq; 
	//char* szIp; 
	////��ʼ��ifconf 
	//ifconf.ifc_len = 512; 
	//ifconf.ifc_buf = buf; 

	//if((sockfd = socket(AF_INET, SOCK_DGRAM, 0))<0) 
	//{ 
	//	return -1; 
	//}
	//ioctl(sockfd, SIOCGIFCONF, &ifconf);    //��ȡ���нӿ���Ϣ
	//close(sockfd);
	////������һ��һ���Ļ�ȡIP��ַ 

	//ifreq = (struct ifreq*)buf; 
	//for(i=(ifconf.ifc_len/sizeof(struct ifreq)); i>0; i--) 
	//{ 

	//	szIp = inet_ntoa(((struct sockaddr_in*)&(ifreq->ifr_addr))->sin_addr); 
	//	if(strcmp(szIp,"127.0.0.1")==0)  //�ų�127.0.0.1��������һ�� 
	//	{ 
	//		ifreq++; 
	//		continue; 
	//	}
	//	strcpy(ip,szIp); 
	//	return true; 
	//} 
	return false;
	 

#endif 
}  

 bool base::GetLocalIP2(std::vector<string> & aryIP)  
{  
#ifdef WIN32
	char szIp[32];
	GetLocalIP(szIp);
	aryIP.push_back( szIp );
	
	return true;
#else
	int i=0;
	int sockfd;
	struct ifconf _ifconf;
	char buf[512];
	struct ifreq *ifreq; 
	char* szIp; 
	//��ʼ��ifconf 
	_ifconf.ifc_len = 512; 
	_ifconf.ifc_buf = buf; 

	if((sockfd = socket(AF_INET, SOCK_DGRAM, 0))<0) 
	{ 
		return -1; 
	}
	ioctl(sockfd, SIOCGIFCONF, &_ifconf);    //��ȡ���нӿ���Ϣ
	close(sockfd);
	//������һ��һ���Ļ�ȡIP��ַ 

	ifreq = (struct ifreq*)buf; 
	for(i=(_ifconf.ifc_len/sizeof(struct ifreq)); i>0; i--) 
	{ 

		szIp = inet_ntoa(((struct sockaddr_in*)&(ifreq->ifr_addr))->sin_addr); 
		if(strcmp(szIp,"127.0.0.1")==0)  //�ų�127.0.0.1��������һ�� 
		{ 
			ifreq++; 
			continue; 
		}
		aryIP.push_back(szIp); 
	} 
	return true;
	 

#endif 
}  

 
#ifndef WIN32
static const char *unixTempFileDir(void){
    static const char *azDirs[] = {
        0,
        0,
        "/var/tmp",
        "/usr/tmp",
        "/tmp",
        0        /* List terminator */
    };
    unsigned int i;
    struct stat buf;
    const char *zDir = 0;

 //   static const char * curr_temp_directory  = "../tmp";
  //  HCheckDir("../tmp/");

   // azDirs[0] =curr_temp_directory;

    if( !azDirs[0] )
        azDirs[0] = getenv("TMPDIR");

    for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
        if( zDir==0 ) continue;
        if( stat(zDir, &buf) ) continue;
        if( !S_ISDIR(buf.st_mode) ) continue;
        if( access(zDir, 07) ) continue;
        break;
    }
    return zDir;
}
#endif

extern bool MY_PRINTF_TAG;
#include <stdarg.h> 
void base::my_printf(const char * format, ...)
{
	if( MY_PRINTF_TAG == 1 ) 
	{
		char msg_buf[4096];
		va_list args; 
		va_start(args, format);
		vsnprintf(msg_buf, 4096, format, args); 
		va_end(args);
	#ifdef WIN32
		TRACE("%s", msg_buf);
	#else 
		printf("%s", msg_buf);
	#endif
	}
}

void base::MyLog(unsigned char level, const char * format, ...)
{
	if( MY_PRINTF_TAG == 1 ) 
	{
		if( level == 2 ) { 
			char msg_buf[4096];
			va_list args; 
			va_start(args, format);
			vsnprintf(msg_buf, 4096, format, args); 
			va_end(args);
			#ifdef WIN32
				TRACE("%s", msg_buf);
			#else 
				printf("%s", msg_buf);
			#endif
		}
	}
}


bool  base::StringSplit_ByChar( const char * split , const char* source, char * left, char * right )
{ 
	if( split == NULL || source == NULL || strlen(split) <= 0 || strlen(source) <= 0 ) { 
		return false;
	} 
  
	string str = source;

	int index = str.find(split, 0);  

	if( index < 0 ) return false;

	string strLeft  = str.substr(0, index);
	string strRight = str.substr( index+1 , str.length() - index );

	strcpy(left, strLeft.c_str());
	
	strcpy(right, strRight.c_str() );

	return true;
}

string  base::toTimeString(time_t tt, bool IsBjTime )
 {
	//time_t lastTime = time(NULL) ; 
	struct tm *p = localtime(&tt);  

	int year  = p->tm_year+1900;
	int month = p->tm_mon+1;
	int day   = p->tm_mday; 
	int Hour   = p->tm_hour; 
	int Minute = p->tm_min;
	int second = p->tm_sec;

	char   chrToken[64] = {0} ;
	if( !IsBjTime ) {
		sprintf(chrToken, "%04d-%02d-%02dT%02d:%02d:%02dZ", p->tm_year+1900, p->tm_mon+1, p->tm_mday, p->tm_hour,p->tm_min, p->tm_sec);
	}
	else {
		sprintf(chrToken, "%04d-%02d-%02d %02d:%02d:%02d", p->tm_year+1900, p->tm_mon+1, p->tm_mday, p->tm_hour,p->tm_min, p->tm_sec);
	}

	return chrToken;
 }


int base::TimeFormatToInt( char * pTimeFormat, bool IsBjTime  )
{
	if( pTimeFormat == NULL) return 0;

	int year, month, day, hour, min, sec;

	//2000-01-01T00:06:31Z
	if( !IsBjTime ) {
		//2000-01-01T00:06:31Z
		sscanf(pTimeFormat, "%4d-%02d-%02dT%02d:%02d:%02dZ", &year, &month, &day, &hour, &min, &sec );
	}
	else{
		sscanf(pTimeFormat, "%4d-%02d-%02d %02d:%02d:%02d ", &year, &month, &day, &hour, &min, &sec );
	}	

	struct tm  tm;

	tm.tm_year = year - 1900 ;
	tm.tm_mon  = month - 1;
	tm.tm_mday = day;
	tm.tm_hour = hour;
	tm.tm_min  = min;
	tm.tm_sec  = sec;

	time_t tt = mktime(&tm);

	return tt;
};

 
 
unsigned char base::bcd_decimal(unsigned char bcd)
{
	return bcd-(bcd >> 4)*6;
}
unsigned char base::decimal_bcd(unsigned char decimal)
{
	return (unsigned char) (decimal+(decimal / 10)*6);
} 

void base::bcd_to_decimal(char * bcd_code, int bcd_len, char* decimalBuf)
{
	if( bcd_code == NULL || bcd_len <= 0 || decimalBuf == NULL ) return;
 
	for( int i=0; i<bcd_len; i++ )
	{
		char  tmpBuf[2] = {0};
		sprintf(tmpBuf, "%02d", bcd_decimal(bcd_code[i]));

		strcat(decimalBuf, tmpBuf);
	} 
	 
} 


#ifdef WIN32
//#include "windows.h"
//#define thread_return_type void*
//typedef thread_return_type (*thread_fn)(void*); 
//void * base::Thread_start(thread_fn fn, void* parameter)
//{
// 
//	DWORD ThreadId = 0; 
//  
//	HANDLE handle = CreateThread(   NULL,
//									0,
//									(LPTHREAD_START_ROUTINE)fn,
//									(LPVOID)parameter,
//									0,
//									&ThreadId );
//
//	if( handle == NULL )
//	{ 
//	}
//
//	return handle;
//}



	 
#else  
thread_type base::Thread_start ( 
		  void* (*lpStartAddress)(void*)  ,
		  void*  ThreadParameter 
		)
{                    
             
	pthread_t   threadId;
	pthread_attr_t attr;

	pthread_attr_init(&attr);
	pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);

	pthread_create(&threadId, &attr, (void*(*)(void*))lpStartAddress, ThreadParameter);


	pthread_attr_destroy(&attr); 
	
	return threadId;
}

#endif

